package com.workManager.controller;

import com.workManager.base.BaseController;
import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;


@Controller
@RequestMapping("/download")
public class DownloadController extends BaseController {
    @RequestMapping("/download")
    public void download(HttpServletResponse response, String fileName) throws IOException {
        fileName = new String(fileName.getBytes("ISO-8859-1"),"UTF-8");
        //取得根目录路径
        String path=getClass().getResource("/file/"+fileName).getFile().toString();
//        File file=new File(path);
//        HttpHeaders headers = new HttpHeaders();
//        headers.setContentDispositionFormData("attachment", fileName);
//        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        //return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);



        //1.设置文件ContentType类型，这样设置，会自动判断下载文件类型
        response.setContentType("multipart/form-data");
        //2.设置文件头：最后一个参数是设置下载文件名(假如我们叫a.pdf)
        response.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(fileName,"UTF-8"));
        ServletOutputStream out;
        //通过文件路径获得File对象(假如此路径中有一个download.pdf文件)
        File file = new File(path);
        FileInputStream inputStream = null;
        try {
            inputStream = new FileInputStream(file);

            //3.通过response获取ServletOutputStream对象(out)
            out = response.getOutputStream();

            int b = 0;
            byte[] buffer = new byte[512];
            while ((b=inputStream.read(buffer))!=-1){
                out.write(buffer,0,b);
            }
            out.flush();
            inputStream.close();
            out.close();


        } catch (IOException e) {
            e.printStackTrace();
        } finally{
            if (null!=inputStream){
                inputStream.close();
            }
        }
    }
}
